import { useBoolean } from '@/hooks/useBoolean.js'
import Service from '@/utils/service.js'

export function useFileDownloader(url, fileName) {
  const [isLoading, toggleLoading] = useBoolean(false)
  const downloadFile = async () => {
    try {
      toggleLoading(true)
      const res = await Service.getBlobAction(url)
      const objectUrl = window.URL.createObjectURL(new Blob([res], { type: 'application/octet-stream' }))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = objectUrl
      link.setAttribute('download', `${fileName}.xlsx`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(objectUrl)
    } catch (e) {
    } finally {
      toggleLoading(false)
    }
  }

  return {
    isLoading,
    downloadFile,
  }
}
